package com.orangelife.service.contact.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;

import com.orangelife.common.MybaitsGenericDaoSubLogic;
import com.orangelife.exception.AppBizException;
import com.orangelife.service.contact.IContactService;
import com.orangelife.service.contact.modal.ContactDto;
import com.orangelife.utils.IdUtil;

@Service("contactService")
public class ContactServiceImpl extends MybaitsGenericDaoSubLogic implements IContactService{

	@Override
	public int updateContac(ContactDto contactDto) throws AppBizException {
		
	if(contactDto.getContactID()==null){
			
			throw new AppBizException(120001, "联系人ID不能为空");
			
		}
		
		
		// TODO Auto-generated method stub
	 return this.getSqlSession().update("PropFeeContactMapper.updateByPrimaryKeySelective", contactDto);
	}

	@Override
	public int addContact(ContactDto contactDto) throws AppBizException {
		
		
		
		if(contactDto.getContactID()==null){
			
			contactDto.setContactID(IdUtil.getuuId());
			
		}
		// TODO Auto-generated method stub
		return this.getSqlSession().insert("PropFeeContactMapper.insertSelective", contactDto);
	}

	@Override
	public ContactDto getContactDetail(String contactID) throws AppBizException {
		// TODO Auto-generated method stub
		return this.getSqlSession().selectOne("PropFeeContactMapper.selectByPrimaryKey", contactID);
	}

	@Override
	public List<ContactDto> getContactByApartmentID(String apartmentID,
			String type) throws AppBizException {
		
		Map<String,Object> param=new HashMap<String ,Object>();
		param.put("type", type);
		param.put("apartmentID", apartmentID);
		
		List<ContactDto> l=this.getSqlSession().selectList("PropFeeContactMapper.selectByapartmentID", param);
		return l;
	}

	@Override
	public int setContactByApartmentID(String ApartmentID,
			String type, String phone) throws AppBizException {

		List<ContactDto> ll =this.getContactByApartmentID(ApartmentID, type);
		int n=0;
		
		this.updateAllNoDefault(ApartmentID);
		if(ll==null||ll.size()==0){
			ContactDto l=new ContactDto();
			l.setPhone(phone);
			l.setType(type);
			l.setTscreate(new Date());
			l.setItemStat("1");
			l.setIsDefault("1");
			l.setApartmentID(ApartmentID);
			n=this.addContact(l);
			
		}else{
			ContactDto l=ll.get(0);
			l.setType(type);
			l.setPhone(phone);
			l.setTsedit(new Date());
			l.setIsDefault("1");
			n=this.updateContac(l);
			
		}
		return n;
		
	}

	@Override
	public int updateAllNoDefault(String apartmentID) throws AppBizException {
		// TODO Auto-generated method stub
		
		return 		this.getSqlSession().update("PropFeeContactMapper.updateAllNoDefault", apartmentID);

	}
	
}
